<template>
  <div>
    <div class="box">
      <select v-model="ShopObj.type">
        <option value="0" disabled>请选择</option>
        <option v-for="(v,i) in options" :key="i" :value="i+1">{{v}}</option>
      </select>
      <input type="text" v-focus ref="ipt" v-model="ShopObj.shop" />
      <button @click="submit">提交</button>
    </div>
    <List v-for="(item,index) in shopping" :item="item" :key="index"/>
  </div>
</template>

<script>
import List from "./List";
import imgUrl from "../../imgs/9-13.jpg";
export default {
  data() {
    return {
      options: ["学习用品", "生活用品", "体育用品", "野炊用品", "医学用品"],
      ShopObj: {
        type: "0",
        shop: ""
      },
      shopping: []
    };
  },
  methods: {
    submit() {
      let ShopObj = JSON.parse(JSON.stringify(this.ShopObj));
      if (this.ShopObj.type && this.ShopObj.shop) {
        let isShop = this.shopping.find(v => {
          return v.type == this.ShopObj.type;
        });
        if (isShop) {
          isShop.children.push({
            img: imgUrl,
            name: ShopObj.shop
          });
        } else {
          let obj = {
            type: ShopObj.type,
            children: []
          };
          obj.children.push({
            img: imgUrl,
            name: ShopObj.shop
          });
          this.shopping.push(obj);
        }
        this.ShopObj.shop = "";
      } else {
        alert("请选择或添加数据！！！");
      }
      this.$refs.ipt.focus();
    }
  },
  directives: {
    focus: {
      inserted(el) {
        el.focus();
      }
    }
  },
  components: {
    List
  }
};
</script>

<style scoped>
* {
  padding: 0;
  margin: 0;
}

.box {
  display: flex;
}

.box select {
  height: 30px;
}
.box input {
  height: 27px;
}
.box button {
  width: 50px;
  height: 30px;
  background-color: #00f;
  border: none;
  color: #ffffff;
}
</style>